package com.jg.myproject.module.logins;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jg.myproject.api.Const;
import com.jg.myproject.api.bean.BaseEntity;
import com.jg.myproject.api.bean.UserBean;
import com.jg.myproject.api.bean.reponse.CommonReponseBean;
import com.jg.myproject.api.bean.request.LoginType;
import com.jg.myproject.module.base.BaseActivity;
import com.jg.myproject.module.projectinfo.ProjectListActivity;
import com.jg.myproject.presenter.LoginPresenter;
import com.jg.myproject.pview.ILoginView;
import com.jg.myproject.utils.KeyboardWatcher;
import com.jg.myproject.utils.RxSPTool;
import com.jg.myproject.widget.dialog.IpDialog;
import com.vondear.rxtools.view.RxToast;
import com.zcr.myproject.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by zhengchengrong on 2017/9/4.
 */
public class LoginActivity extends BaseActivity implements ILoginView, KeyboardWatcher.SoftKeyboardStateListener {
    @BindView(R.id.logo)
    TextView logo;
    @BindView(R.id.iv_clean_phone)
    ImageView ivCleanPhone;
    @BindView(R.id.clean_password)
    ImageView cleanPassword;
    @BindView(R.id.iv_show_pwd)
    ImageView ivShowPwd;
    @BindView(R.id.login)
    TextView mLogin;
    @BindView(R.id.ip)
    TextView mIp;
    private ProgressDialog dialog;
    //动画
    private KeyboardWatcher keyboardWatcher;
    private int screenHeight = 0;//屏幕高度
    private float scale = 0.7f; //logo缩放比例
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.phoneNum)
    EditText phoneNum;
    @BindView(R.id.agree)
    CheckedTextView agree;
    @BindView(R.id.ck_phone)
    CheckedTextView ckphone;
    @BindView(R.id.ck_psw)
    CheckedTextView ckpsw;
    @BindView(R.id.body)
    LinearLayout body;
    LoginPresenter mLoginPresenter;
    String PHONENUM = "phonenum";
    String PASSWORD = "password";
    String ISCHECK = "ischeck";
    private boolean ischeck;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void initViews() {
        mLoginPresenter = new LoginPresenter(this);
        String username =RxSPTool.getString(this,Const.USERNAME);
        String passwrod =RxSPTool.getString(this,Const.PASSWORD);
        phoneNum.setText(username);
        password.setText(passwrod);
        screenHeight = this.getResources().getDisplayMetrics().heightPixels; //获取屏幕高度
        phoneNum.addTextChangedListener(new textChangedListen(LoginType.phone));
        password.addTextChangedListener(new textChangedListen(LoginType.password));
        keyboardWatcher = new KeyboardWatcher(findViewById(Window.ID_ANDROID_CONTENT));
        keyboardWatcher.addSoftKeyboardStateListener(this);
    }

    @Override
    protected void updateViews(boolean isRefresh) {
    }

    private boolean flag = false;

    @OnClick({R.id.iv_clean_phone, R.id.clean_password, R.id.iv_show_pwd, R.id.login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_clean_phone:
                phoneNum.setText("");
                break;
            case R.id.clean_password:
                password.setText("");
                break;
            case R.id.login:
                if(TextUtils.isEmpty(phoneNum.getText())){
                    RxToast.showToast(Const.LOGIN_NO_USERNAME);
                    return;
                }
                if(TextUtils.isEmpty(password.getText())){
                    RxToast.showToast(Const.LOGIN_NO_PWD);
                    return;
                }
                // 登陆
                dialog = new ProgressDialog(this);
                dialog.setCanceledOnTouchOutside(false);
                dialog.setCancelable(true);
                dialog.setTitle("正在登录...");
                dialog.show();
                UserBean userBean = new UserBean();
                userBean.setUsername(phoneNum.getText().toString());
                userBean.setPassword(password.getText().toString());
                mLoginPresenter.getData(userBean);//登陆
                break;
            case R.id.iv_show_pwd:
                if (flag == true) {
                    password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    ivShowPwd.setImageResource(R.drawable.pass_gone);
                    flag = false;
                } else {
                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    ivShowPwd.setImageResource(R.drawable.pass_visuable);
                    flag = true;
                }
                String pwd = password.getText().toString();
                if (!TextUtils.isEmpty(pwd))
                    password.setSelection(pwd.length());
                break;
        }
    }
    @OnClick(R.id.ip)
    void ip() {  //IP设置
        new IpDialog(this).show();
    }
    @Override
    public void getReponseBeans(BaseEntity<CommonReponseBean> bean) {
        dialog.dismiss();
        RxSPTool.putString(LoginActivity.this, Const.USERID, bean.getBeans().get(0).getUserId());
        RxSPTool.putString(LoginActivity.this, Const.USERNAME, bean.getBeans().get(0).getUsername());
        RxSPTool.putString(LoginActivity.this, Const.CUSTOMERID, bean.getBeans().get(0).getDisplayName());
        RxSPTool.putString(LoginActivity.this, Const.PASSWORD,password.getText().toString());

        // 登陆
        toNextActivityAndAnim(ProjectListActivity.class, true);
    }


    class textChangedListen implements TextWatcher {
        LoginType type;

        public textChangedListen(LoginType type) {
            this.type = type;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (type == LoginType.phone) {
                if (!TextUtils.isEmpty(s) && ivCleanPhone.getVisibility() == View.GONE) {
                    ivCleanPhone.setVisibility(View.VISIBLE);
                    ckphone.setChecked(true);
                } else if (TextUtils.isEmpty(s)) {
                    ivCleanPhone.setVisibility(View.GONE);
                    ckphone.setChecked(false);
                }
            }
            if (type == LoginType.password) {
                if (!TextUtils.isEmpty(s) && cleanPassword.getVisibility() == View.GONE) {
                    cleanPassword.setVisibility(View.VISIBLE);
                    ckpsw.setChecked(true);
                } else if (TextUtils.isEmpty(s)) {
                    cleanPassword.setVisibility(View.GONE);
                    ckpsw.setChecked(false);
                }
                if (s.toString().isEmpty())
                    return;
                if (!s.toString().matches("[A-Za-z0-9]+")) {
                    String temp = s.toString();
                    Toast.makeText(LoginActivity.this, "请输入数字或字母", Toast.LENGTH_SHORT).show();
                    s.delete(temp.length() - 1, temp.length());
                    password.setSelection(s.length());
                }
            }
        }
    }

    //以下是实现login动画
    @Override
    public void onSoftKeyboardOpened(int keyboardHeightInPx) {
        int[] location = new int[2];
        body.getLocationOnScreen(location); //获取body在屏幕中的坐标,控件左上角
        int x = location[0];
        int y = location[1];
        int bottom = screenHeight - (y + body.getHeight());
        if (keyboardHeightInPx > bottom) {
            ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(body, "translationY", 0.0f, -(keyboardHeightInPx - bottom));
            mAnimatorTranslateY.setDuration(300);
            mAnimatorTranslateY.setInterpolator(new AccelerateDecelerateInterpolator());
            mAnimatorTranslateY.start();
            zoomIn(logo, keyboardHeightInPx - bottom);

        }
    }

    @Override
    public void onSoftKeyboardClosed() {
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(body, "translationY", body.getTranslationY(), 0);
        mAnimatorTranslateY.setDuration(300);
        mAnimatorTranslateY.setInterpolator(new AccelerateDecelerateInterpolator());
        mAnimatorTranslateY.start();
        zoomOut(logo);
    }

    /**
     * 缩小
     * @param view
     */
    public void zoomIn(final View view, float dist) {
        view.setPivotY(view.getHeight());
        view.setPivotX(view.getWidth() / 2);
        AnimatorSet mAnimatorSet = new AnimatorSet();
        ObjectAnimator mAnimatorScaleX = ObjectAnimator.ofFloat(view, "scaleX", 1.0f, scale);
        ObjectAnimator mAnimatorScaleY = ObjectAnimator.ofFloat(view, "scaleY", 1.0f, scale);
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(view, "translationY", 0.0f, -dist);
        mAnimatorSet.play(mAnimatorTranslateY).with(mAnimatorScaleX).with(mAnimatorScaleY);
        mAnimatorSet.setDuration(300);
        mAnimatorSet.start();
    }

    /**
     * f放大
     *
     * @param view
     */
    public void zoomOut(final View view) {
        if (view.getTranslationY() == 0) {
            return;
        }
        view.setPivotY(view.getHeight());
        view.setPivotX(view.getWidth() / 2);
        AnimatorSet mAnimatorSet = new AnimatorSet();
        ObjectAnimator mAnimatorScaleX = ObjectAnimator.ofFloat(view, "scaleX", scale, 1.0f);
        ObjectAnimator mAnimatorScaleY = ObjectAnimator.ofFloat(view, "scaleY", scale, 1.0f);
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(view, "translationY", view.getTranslationY(), 0);
        mAnimatorSet.play(mAnimatorTranslateY).with(mAnimatorScaleX).with(mAnimatorScaleY);
        mAnimatorSet.setDuration(300);
        mAnimatorSet.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        keyboardWatcher.removeSoftKeyboardStateListener(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            Dialog dialog = new AlertDialog.Builder(this).setTitle("操作提示")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                            System.exit(0);
                        }
                    }).setMessage("您确定退出?").setIcon(android.R.drawable.ic_dialog_info).setNegativeButton("取消", null).create();
            dialog.show();
            return false;
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
            // return flagf;
            // 监控/拦截菜单键
        } else if (keyCode == KeyEvent.KEYCODE_HOME) {
            // return flagf;
            // 由于Home键为系统键，此处不能捕获，需要重写onAttachedToWindow()
        }
        return super.onKeyDown(keyCode, event);
    }
}

